<?php
namespace app\wypadmin\controller;
use think\Request;

/**
 * 房源类别
 */
class User extends Base
{
	protected $user;

	protected function _initialize(){
		parent::_initialize();
		$this->user = Model('User');
	}

	public function add(){

		$this->assign('webname',$this->webname);
		return $this->fetch();
	}

	public function saveuser(){
		$request = Request::instance();

		if (!$request->isPost()) {
			echo '<script>alert("更新失败");history.back();"</script>';
			return;
		}

		if ($request->post('pwd') != $request->post('pwded')) {
			echo '密码错误';
			return;
		}

		$data['id'] 		= $request->post('id');

		if ($data['id']) {
			if ($request->post('pwd') == '' && $request->post('pwded') == '') {
				$data['username'] 	= $request->post('username');
			}else{
				$data['usercate'] 	= $request->post('usercate');
				$data['username'] 	= $request->post('username');
				$data['pwd'] 		= md5($request->post('pwd'));
			}
			$res = $this->user->save($data,['id'=>$data['id']]);
			if ($res) {
				echo '<script>alert("更新完成");location.href="' . url('lst') . '"</script>';
			}else{
				echo '<script>alert("更新失败");history.back();"</script>';
			}
		}else{		
			$data['usercate'] 	= $request->post('usercate');
			$data['username'] 	= $request->post('username');
			$data['pwd'] 		= md5($request->post('pwd'));
			$data['adddate']	= time();	

			$res = $this->user->save($data);
			if ($res) {
				echo '<script>alert("添加完成");location.href="' . url('add') . '"</script>';
			}else{
				echo '<script>alert("添加失败");history.back();"</script>';
			}
		}
	}

	public function edit($id){
		$info	= $this->user->getOne($id);
		$option 	= '';
		$this->assign([
			'info' 		=> $info
		]);
		$this->assign('webname',$this->webname);
		return $this->fetch();
	}

	public function lst(){
		$list = $this->user->getList();
		$page = $list->render();
		$tr = '';
		foreach ($list as $v) {
			$usercate = $v['usercate'];
			if ($usercate == 0) {
				$cate = '管理员';
			}else if($usercate == 1){
				$cate = '信息录入';
			}
			$tr .= '
					<tr>
						<td>' . $v['id'] . '</td>
						<td>' . $v['username'] . '</td>
						<td>' . $cate . '</td>
						<td>' . date('Y-m-d',$v['adddate']) . '</td>
						<td>
							<a href="' . url('edit','id=' .$v['id']) . '"><span class="glyphicon glyphicon-pencil"></span>编辑</a> | 
							<a href="javascript:del(' . $v['id'] . ');"><span class="glyphicon glyphicon-trash"></span>删除</a>
						</td>
					</tr>';
		}

		$this->assign('webname',$this->webname);
		$this->assign('tr',$tr);
		$this->assign('page',$page);
		$this->assign('count',count($list));
		return $this->fetch();
	}

	public function del($id){
		$where = [
			'id' => $id,
		];
		$res = $this->user->where($where)->delete();
		if ($res) {
			echo '<script>alert("删除完成");location.href="' . url('lst') . '"</script>';
		}else{
			echo '<script>alert("删除失败");history.back();"</script>';
		}
	}
}